<template>
    <div class="page-wrap" v-loading="loading">
        <div class="page-cont">
            <h-section title="字典树">
                <flexbox style="margin-bottom: 8px">
                    <a-input-search v-model:value="searchValue" style="width: 400px" placeholder="请输入关键字" enter-button @search="handleSearch" />
                    <a-button class="margin-l-8" type="primary" @click="handleCreateRoot"> <PlusOutlined /><span>新增根节点</span> </a-button>
                </flexbox>
                <a-tree :tree-data="treeData" :replaceFields="{ children: 'pmpDictionaryDTOs', key: 'id', title: 'dimensionName' }" :autoExpandParent="autoExpandParent" v-model:expandedKeys="expandedKeys">
                    <template v-slot:title="{ dimensionName, id, code, level, fatherId }">
                        <flexbox class="title-wrap">
                            <span v-if="dimensionName.indexOf(searchValue) > -1">
                                {{ dimensionName.substr(0, dimensionName.indexOf(searchValue)) }}
                                <span style="color: #f50">{{ searchValue }}</span>
                                {{ dimensionName.substr(dimensionName.indexOf(searchValue) + searchValue.length) }}
                            </span>
                            <span v-else>{{ dimensionName }}</span>
                            <!-- 阶段和状态节点或者阶段和状态下的子节点无法修改和新增 -->
                            <div class="icon-cont" v-if="id !== 19 && id !== 21 && fatherId !== 19 && fatherId !== 21">
                                <PlusOutlined @click.stop="handleCreate({ id, level, dimensionName, fatherId })" />
                                <EditOutlined @click.stop="handleEdit({ id, code, level, dimensionName, fatherId })" />
                                <CloseOutlined @click.stop="handleDelete(id, dimensionName)" />
                            </div>
                        </flexbox>
                    </template>
                </a-tree>
            </h-section>
        </div>
        <form-modal ref="createModalRef" @success="getList" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { useMessage } from '@/hooks/common/useMessage';
import { transformToList, getParentKey, getParent } from '@/utils/tree';
import FormModal from './components/formModal.vue';
import { PlusOutlined, EditOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { defineComponent, reactive, toRefs, ref, unref } from 'vue';
import { message } from 'ant-design-vue/es';
export default defineComponent({
    name: 'dicTree',
    components: {
        PlusOutlined,
        EditOutlined,
        CloseOutlined,
        FormModal
    },
    setup() {
        const createModalRef = ref<any>();
        const state = reactive<any>({
            treeData: [],
            expandedKeys: [],
            autoExpandParent: false,
            searchValue: '',
            loading: false
        });
        // 新增根节点
        const handleCreateRoot = () => {
            unref(createModalRef).open({ type: 'createRoot' });
        };
        // 新增普通
        const handleCreate = (data: any) => {
            const node: any = getParent(data.id, state.treeData, {
                keyField: 'id',
                childrenField: 'pmpDictionaryDTOs'
            });
            data.fatherName = node ? node.dimensionName : '';
            unref(createModalRef).open({
                type: 'create',
                data
            });
        };
        // 编辑普通
        const handleEdit = (data: any) => {
            const node: any = getParent(data.id, state.treeData, {
                keyField: 'id',
                childrenField: 'pmpDictionaryDTOs'
            });
            data.fatherName = node ? node.dimensionName : '';
            unref(createModalRef).open({
                type: 'edit',
                data
            });
        };
        // 删除
        const handleDelete = (id, dimensionName) => {
            const { createConfirm } = useMessage();
            createConfirm({
                title: `确认删除【${dimensionName}】数据？`,
                iconType: 'danger',
                onOk: async () => {
                    const query = {
                        id
                    };
                    const { success, errorMsg } = await api.dicModel.delete(query);
                    if (success) {
                        message.success('删除成功');
                        getList();
                    } else {
                        message.error(errorMsg);
                    }
                }
            });
        };
        const getList = async () => {
            state.loading = true;
            const { success, moule } = await api.dicModel.firstPage();
            if (success) {
                state.treeData = [...moule];
                !state.expandedKeys.length && getDefaultExpandKeys();
            }
            state.loading = false;
        };
        // 默认展开节点
        const getDefaultExpandKeys = () => {
            const arr = state.treeData.filter((item) => item.dimensionName === '业务需求');
            state.expandedKeys = arr.map((item) => item.id);
        };
        const handleSearch = (val: string) => {
            const dataList = transformToList(state.treeData, {
                keyField: 'id',
                titleField: 'dimensionName',
                childrenField: 'pmpDictionaryDTOs'
            });
            const expandedKeys = dataList
                .map((item: any) => {
                    if (item.dimensionName.indexOf(val) > -1) {
                        return getParentKey(item.id, state.treeData, {
                            keyField: 'id',
                            childrenField: 'pmpDictionaryDTOs'
                        });
                    }
                    return null;
                })
                .filter((item, i, self) => item && self.indexOf(item) === i);
            state.searchValue = val;
            state.expandedKeys = expandedKeys;
            state.autoExpandParent = true;
        };

        getList();
        return {
            ...toRefs(state),
            createModalRef,
            handleCreateRoot,
            handleSearch,
            handleCreate,
            handleEdit,
            getList,
            handleDelete
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    height: 100%;
    position: relative;
    .page-cont {
        min-height: 516px;
        background: #fff;
        .title-wrap {
            .icon-cont {
                display: none;
                .anticon {
                    margin-left: 8px;
                }
            }
            &:hover {
                .icon-cont {
                    display: block;
                }
            }
        }
    }
}
</style>